/**
 * 
 */
package com.nari.heatshare.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.heatshare.model.IUserShareResult;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.rescontroller.dao.IResourceAccessControlDao;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-19
 */
public class UserShareResultDaoImpl extends GenericDaoImpl<IUserShareResult, String> 
		implements IUserShareResultDao {
	private IResourceAccessControlDao iResourceAccessControlDao;

	/**
	 * 分页查询用户分摊结果
	 * @param projectUID 所属项目(可选)
	 * @param communityUID 所属小区(可选)
	 * @param buildingUID 所属楼栋(可选)
	 * @param heatRoomUID 所属热用户(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-6
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IUserShareResult> queryUserShareResultPage(String projectUID, 
			String communityUID, String buildingUID, String heatRoomUID, 
			PageCond pageCond) throws Exception {
		Criteria listCriteria = this.getCurrentSession().createCriteria(IUserShareResult.class);
		Criteria countCriteria = this.getCurrentSession().createCriteria(IUserShareResult.class);
		//所属项目
		if (projectUID!=null && !"".equals(projectUID.trim())) {
			listCriteria.add(Restrictions.eq("projectID", projectUID.trim()));
			countCriteria.add(Restrictions.eq("projectID", projectUID.trim()));
		}
		//所属小区
		if (communityUID!=null && !"".equals(communityUID.trim())) {
			listCriteria.add(Restrictions.eq("communityID", communityUID.trim()));
			countCriteria.add(Restrictions.eq("communityID", communityUID.trim()));
		}
		//所属楼栋
		if (buildingUID!=null && !"".equals(buildingUID.trim())) {
			listCriteria.add(Restrictions.eq("buildingID", buildingUID.trim()));
			countCriteria.add(Restrictions.eq("buildingID", buildingUID.trim()));
		}
		//所属热用户
		if (heatRoomUID!=null && !"".equals(heatRoomUID.trim())) {
			listCriteria.add(Restrictions.eq("roomId", heatRoomUID.trim()));
			countCriteria.add(Restrictions.eq("roomId", heatRoomUID.trim()));
		}
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResSql();
		if(!"".equals(authorityRes)) {
			//这是一个直接与底层数据库耦合的查询，注意避免数模更改带来的系统问题
			listCriteria.add(Restrictions.sqlRestriction("{alias}.t_project_id in("+authorityRes+")"));
			countCriteria.add(Restrictions.sqlRestriction("{alias}.t_project_id in("+authorityRes+")"));
		}
		//统计结果集个数
		int total = ((Long)countCriteria.setProjection(Projections.rowCount()).list().get(0)).intValue();
		//结果集排序
		listCriteria.addOrder(Order.desc("startDate")).addOrder(Order.desc("endDate"));
		//结果集分页
		listCriteria.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		//构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<IUserShareResult> userShareResultPage = new ResultWithPageCond<IUserShareResult>();
		userShareResultPage.setList(listCriteria.list());
		userShareResultPage.setPageCond(pageCond);
		return userShareResultPage;
	}
	
	/**
	 * 通过分摊域分摊ID批量删除对应的用户分摊
	 * @param areaResultUID
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-8
	 */
	public void deleteUserResultByAreaResultUID(String areaResultUID) throws Exception {
		String hsql = "delete from IUserShareResult usr " +
				"where usr.areaResultID='"+areaResultUID+"'";
		this.runFormatHSql(hsql);
	}
	
	/**
	 * 通过分摊域分摊ID分页查询所属的用户分摊列表
	 * @param areaResultUID 分摊域分摊ID(必填)
	 * @param roomOwner 户主姓名(可选)
	 * @param houseNo 门牌号(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-16
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IUserShareResult> queryUserPageByAreaResultUID(String areaResultUID, 
			String roomOwner, String houseNo, PageCond pageCond) throws Exception {
		int total = 0;
		List<IUserShareResult> userResultList = new ArrayList<IUserShareResult>();
		if(areaResultUID!=null && !"".equals(areaResultUID)) {
			Criteria listCriteria = this.getCurrentSession().createCriteria(IUserShareResult.class);
			Criteria countCriteria = this.getCurrentSession().createCriteria(IUserShareResult.class);
			//所属分摊域分摊
			if (areaResultUID!=null && !"".equals(areaResultUID.trim())) {
				listCriteria.add(Restrictions.eq("areaResultID", areaResultUID.trim()));
				countCriteria.add(Restrictions.eq("areaResultID", areaResultUID.trim()));
			}
			//户主姓名
			if(roomOwner!=null && !"".equals(roomOwner.trim())) {
				listCriteria.add(Restrictions.ilike("roomOwner", roomOwner.trim().toLowerCase(), MatchMode.ANYWHERE));
				countCriteria.add(Restrictions.ilike("roomOwner", roomOwner.trim().toLowerCase(), MatchMode.ANYWHERE));
			}
			//门牌号
			if(houseNo!=null && !"".equals(houseNo.trim())) {
				listCriteria.add(Restrictions.ilike("houseNo", houseNo.trim().toLowerCase(), MatchMode.ANYWHERE));
				countCriteria.add(Restrictions.ilike("houseNo", houseNo.trim().toLowerCase(), MatchMode.ANYWHERE));
			}
			//统计结果集个数
			total = ((Long)countCriteria.setProjection(Projections.rowCount()).list().get(0)).intValue();
			//结果集排序
			listCriteria.addOrder(Order.desc("startDate")).addOrder(Order.desc("endDate"));
			//结果集分页
			listCriteria.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
			userResultList = listCriteria.list();
		}
		//构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<IUserShareResult> userShareResultPage = new ResultWithPageCond<IUserShareResult>();
		userShareResultPage.setList(userResultList);
		userShareResultPage.setPageCond(pageCond);
		return userShareResultPage;
	}
	
	/**
	 * 统计热用户在指定时段内的分摊账单数量
	 * @param roomId
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-4-30
	 */
	public int countUserResultByPeriod(String roomId, Date startDate, Date endDate) throws Exception {
		String hsql = "select count(*) from IUserShareResult usr " +
				"where usr.roomId='"+roomId+"' " +
				"and usr.startDate>=:startDate and usr.endDate<=:endDate";
		Query query = this.getCurrentSession().createQuery(hsql);
		//设置时段
		query.setTimestamp("startDate", startDate).setTimestamp("endDate", endDate);
		return ((Long)query.uniqueResult()).intValue();
	}
	
	/**
	 * 查询热用户在指定时段内的分摊账单(取参考散热量的最大值)
	 * @param roomId
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-5-3
	 */
	@SuppressWarnings("unchecked")
	public List<IUserShareResult> queryUserResultByPeriod(String roomId, Date startDate, 
			Date endDate) throws Exception {
		String hsql = "from IUserShareResult usr " +
				"where usr.roomId='"+roomId+"' " +
				"and usr.startDate>=:startDate and usr.endDate<=:endDate " +
				"order by referHeatConsume desc";
		Query query = this.getCurrentSession().createQuery(hsql);
		//设置时段
		query.setTimestamp("startDate", startDate).setTimestamp("endDate", endDate);
		return query.list();
	}

	/**
	 * @return the iResourceAccessControlDao
	 */
	public IResourceAccessControlDao getiResourceAccessControlDao() {
		return iResourceAccessControlDao;
	}

	/**
	 * @param iResourceAccessControlDao the iResourceAccessControlDao to set
	 */
	public void setiResourceAccessControlDao(
			IResourceAccessControlDao iResourceAccessControlDao) {
		this.iResourceAccessControlDao = iResourceAccessControlDao;
	}
	
}
